#!/bin/bash

# RTC AIGC统一部署脚本 - 集合本地、远程和HTTPS部署功能
SERVER_IP="112.124.18.247"
DOMAIN="${1:-$SERVER_IP}"
SSH_KEY="~/.ssh/id_rsa_deploy"
EMAIL="admin@example.com"
MODE="${2:-remote}"  # 部署模式: local/remote/https
CURRENT_DIR=$(pwd)

echo "🚀 RTC AIGC部署工具"

# 检查Docker
if ! docker info > /dev/null 2>&1; then
  echo "❌ Docker未运行"
  exit 1
fi

# 函数: 本地部署
deploy_local() {
  echo "📦 本地部署模式"
  
  # 清理Docker缓存
  docker system prune -f
  
  # 构建并启动服务
  docker-compose up --build -d
  
  echo "✅ 本地部署完成! 访问: http://localhost"
}

# 函数: 远程部署
deploy_remote() {
  echo "📦 远程部署模式"
  
  # 检查已有镜像
  if docker images | grep -q "rtc-aigc-demo-frontend"; then
    echo "✅ 前端镜像已存在"
  else
    echo "🔨 构建前端镜像..."
    docker build -t rtc-aigc-demo-frontend:latest .
  fi
  
  if docker images | grep -q "rtc-aigc-demo-backend"; then
    echo "✅ 后端镜像已存在"
  else
    echo "🔨 构建后端镜像..."
    docker build -t rtc-aigc-demo-backend:latest ./rtc-aigc-server
  fi
  
  # 保存镜像
  docker save rtc-aigc-demo-frontend:latest > frontend.tar
  docker save rtc-aigc-demo-backend:latest > backend.tar
  
  # 上传文件
  ssh -i ${SSH_KEY} -o StrictHostKeyChecking=no root@${SERVER_IP} "mkdir -p /opt/rtc-aigc-demo"
  scp -i ${SSH_KEY} -o StrictHostKeyChecking=no frontend.tar backend.tar root@${SERVER_IP}:/opt/rtc-aigc-demo/
  scp -i ${SSH_KEY} -o StrictHostKeyChecking=no docker-compose.yml nginx.conf root@${SERVER_IP}:/opt/rtc-aigc-demo/
  
  # 创建远程部署脚本
  REMOTE_SCRIPT="cd /opt/rtc-aigc-demo && \
  docker-compose down --remove-orphans && \
  docker rmi -f rtc-aigc-demo-frontend:latest rtc-aigc-demo-backend:latest 2>/dev/null || true && \
  docker load < frontend.tar && \
  docker load < backend.tar && \
  docker image prune -f && \
  docker-compose up -d && \
  rm -f frontend.tar backend.tar"
  
  # 执行远程部署
  ssh -i ${SSH_KEY} -o StrictHostKeyChecking=no root@${SERVER_IP} "${REMOTE_SCRIPT}"
  
  # 清理本地文件
  rm -f frontend.tar backend.tar
  
  echo "✅ 远程部署完成! 访问: http://${SERVER_IP}"
}

# 函数: HTTPS部署
deploy_https() {
  echo "🔒 HTTPS部署模式"
  
  # 检查已有镜像
  if docker images | grep -q "rtc-aigc-demo-frontend"; then
    echo "✅ 使用已有前端镜像"
    docker tag rtc-aigc-demo-frontend:latest rtc-aigc-demo-frontend-https:latest
  else
    echo "❌ 未找到前端镜像，请先运行remote模式部署"
    exit 1
  fi
  
  if docker images | grep -q "rtc-aigc-demo-backend"; then
    echo "✅ 使用已有后端镜像"
    docker tag rtc-aigc-demo-backend:latest rtc-aigc-demo-backend-https:latest
  else
    echo "❌ 未找到后端镜像，请先运行remote模式部署"
    exit 1
  fi
  
  # 保存镜像
  echo "📦 保存镜像..."
  docker save rtc-aigc-demo-frontend-https:latest > frontend-https.tar
  docker save rtc-aigc-demo-backend-https:latest > backend-https.tar
  
  # 创建HTTPS配置文件
  echo "📝 创建HTTPS配置文件..."
  mkdir -p https-config
  
  # 创建Nginx HTTPS配置
  cat > https-config/nginx-https.conf << EOF
server {
    listen 80;
    server_name localhost;
    
    # 将HTTP请求重定向到HTTPS
    return 301 https://\$host\$request_uri;
}

server {
    listen 443 ssl;
    server_name localhost;

    # SSL证书配置
    ssl_certificate /etc/ssl/rtc-aigc.crt;
    ssl_certificate_key /etc/ssl/rtc-aigc.key;
    
    # 优化SSL设置
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers on;
    
    # 启用HSTS
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    
    # 前端文件
    location / {
        root   /usr/share/nginx/html;
        try_files \$uri \$uri/ /index.html;
        
        # 安全相关的响应头
        add_header X-Content-Type-Options "nosniff" always;
        add_header X-Frame-Options "SAMEORIGIN" always;
        add_header X-XSS-Protection "1; mode=block" always;
    }

    # 后端API代理
    location /api/ {
        proxy_pass http://backend:3001/api/;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
    }
}
EOF
  
  # 创建SSL证书生成脚本
  cat > https-config/setup-ssl.sh << 'EOF'
#!/bin/sh
# 检测系统类型
if command -v apt-get >/dev/null 2>&1; then
  # Debian/Ubuntu系统
  apt-get update && apt-get install -y openssl
elif command -v apk >/dev/null 2>&1; then
  # Alpine系统
  apk add --no-cache openssl
elif command -v yum >/dev/null 2>&1; then
  # CentOS/RHEL系统
  yum install -y openssl
else
  echo "无法确定系统包管理器，尝试直接使用openssl"
fi

# 生成自签名证书
DOMAIN="$1"
echo "生成证书: $DOMAIN"
mkdir -p /etc/ssl
openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
  -keyout /etc/ssl/rtc-aigc.key \
  -out /etc/ssl/rtc-aigc.crt \
  -subj "/CN=$DOMAIN" \
  -addext "subjectAltName=IP:$DOMAIN"
EOF
  
  # 创建Docker Compose文件
  cat > https-config/docker-compose-https.yml << EOF
version: '3'
services:
  frontend:
    image: rtc-aigc-demo-frontend-https:latest
    container_name: rtc-frontend-https
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx-https.conf:/etc/nginx/conf.d/default.conf
      - /etc/ssl:/etc/ssl
    depends_on:
      - backend
    restart: always
    
  backend:
    image: rtc-aigc-demo-backend-https:latest
    container_name: rtc-backend-https
    expose:
      - "3001"
    restart: always
EOF
  
  # 上传文件到服务器
  echo "📤 上传文件到服务器..."
  ssh -i ${SSH_KEY} -o StrictHostKeyChecking=no root@${SERVER_IP} "mkdir -p /opt/rtc-aigc-https"
  scp -i ${SSH_KEY} -o StrictHostKeyChecking=no frontend-https.tar backend-https.tar root@${SERVER_IP}:/opt/rtc-aigc-https/
  scp -i ${SSH_KEY} -o StrictHostKeyChecking=no -r https-config/* root@${SERVER_IP}:/opt/rtc-aigc-https/
  
  # 创建远程部署脚本
  REMOTE_SCRIPT="cd /opt/rtc-aigc-https && \
    docker-compose -f docker-compose-https.yml down --remove-orphans 2>/dev/null || true && \
    docker rmi -f rtc-aigc-demo-frontend-https:latest rtc-aigc-demo-backend-https:latest 2>/dev/null || true && \
    docker load < frontend-https.tar && \
    docker load < backend-https.tar && \
    chmod +x setup-ssl.sh && \
    ./setup-ssl.sh \"${DOMAIN}\" && \
    docker-compose -f docker-compose-https.yml up -d && \
    rm -f frontend-https.tar backend-https.tar"
  
  # 执行远程部署
  echo "🚀 执行远程部署..."
  ssh -i ${SSH_KEY} -o StrictHostKeyChecking=no root@${SERVER_IP} "${REMOTE_SCRIPT}"
  
  # 清理本地临时文件
  rm -rf frontend-https.tar backend-https.tar https-config
  
  echo "✅ HTTPS部署完成!"
  echo "🔒 前端: https://${DOMAIN}"
  echo "🔒 后端API: https://${DOMAIN}/api/"
  
  # 检查容器状态和日志
  echo "🔍 检查部署状态..."
  ssh -i ${SSH_KEY} -o StrictHostKeyChecking=no root@${SERVER_IP} "docker ps -a && echo '=== 前端容器日志 ===' && docker logs rtc-frontend-https && echo '=== 后端容器日志 ===' && docker logs rtc-backend-https"
  
  # 测试连接
  echo "🔍 测试连接..."
  ssh -i ${SSH_KEY} -o StrictHostKeyChecking=no root@${SERVER_IP} "curl -k https://localhost/api/ && echo"
}

# 根据模式执行部署
case $MODE in
  local)
    deploy_local
    ;;
  remote)
    deploy_remote
    ;;
  https)
    deploy_https
    ;;
  *)
    echo "❌ 未知部署模式: $MODE"
    echo "💡 用法: ./deploy.sh [域名|IP] [local|remote|https]"
    echo "    例如: ./deploy.sh 112.124.18.247 remote"
    echo "    例如: ./deploy.sh example.com https"
    echo "    例如: ./deploy.sh local (本地部署)"
    exit 1
    ;;
esac
